<?php

class controller_modules extends __registry_controller {

    public $_ = array();
    public $_layout = NULL;
    public $_content_header = 'OPEN';
    public $_content_top = 'OPEN';

    public function __construct() {
        parent::add_object(array(
            'handle_string',
            'handle_upload',
            'handle_paging',
            'model_modules',
            'handle_validate',
            'model_users',
			'handle_permission',
            'model_categories',
            'model_language'
        ));
        $this->_layout = NULL;
    }

    public function index_action() {
	
		/* Check permission */
		$this->per_check_permission();
		
        $limit = 2;
        $res_html = NULL;
        $enseo = isset($this->_seokey[2]) ? $this->_seokey[2] : null;
        $this->_['url_add'] = URL_BASE . 'admin/' . $this->_seokey[1] . '/' . $this->route->rt_get_seokey_act('add') . '/';
        $this->_['url_edit'] = URL_BASE . 'admin/' . $this->_seokey[1] . '/' . $this->route->rt_get_seokey_act('edit') . '/';

        $html = $this->view->view_display('index');
        $arr_block_html = $this->view->view_get_block_html($html);

        $current = intval($enseo) != 0 ? intval($enseo) : 1;
        $total = $this->md_modules_total_list();
       
        if ($total == 0) {
            $res_html = '';
            $this->_['paging'] = '';
            $shtml = $this->view->view_assign($arr_block_html['empty'], $this->_);
        } else {
            $url = URL_BASE . $this->_seokey[0] . '/' . $this->_seokey[1];
            $this->_['paging'] = $this->paging_display($total, $current, $limit, $url, $this->_);

            $rows = $this->md_modules_list(1, $current, $limit);
            $status_href = $this->_seokey[0] . '/' . $this->_seokey[1];

            if (!empty($rows))
                foreach ($rows as $key => $value) {
                    if ($value['Status'] == 'true') {
                        $class_status = "accept";
                        $status = 'false';
                        $sta = "Hiển thị";
                    } else {
                        $class_status = "inactive";
                        $status = 'true';
                        $sta = "Ẩn";
                    }
                    $id = $value['ID'];
                    $change_Status = "change_Status('" . $status_href . "'," . $id . ",'" . $status . "', this)";
                    $delete_module = "delete_module('" . $status_href . "'," . $id . ",this)";
                    $href_edit_module = URL_BASE . "$status_href/chinh-sua/module-" . $id;
                    $res_html .= $this->view->view_assign($arr_block_html['modules'], array(
                        'Name' => $value['Name'],
                        'id' => $value['ID'],
                        'status' => $value['Status'],
                        
                        'Notes' => $value['Notes'],
                        'class_status' => $class_status,
                        'change_Status' => $change_Status,
                        'delete_module' => $delete_module,
                        'Sta' => $sta,
                        'href_edit_module' => $href_edit_module,
                            ));
                }
            $this->_['page'] = $current;
            $this->_['status_href'] = $status_href;

            $shtml = $this->view->view_assign_block($html, array('htmlmodules' => $res_html));
        }
        return $shtml;
    }

    public function index_ajax_action() {
	
		/* Check permission */
		$this->per_check_permission();
		
        $this->_layout = 'NO_LAYOUT';
        
        switch ($this->_seokey[3]) {
            case "change":
                /* admin/he-thong-quan-ly-module/ajax/change/true/1 */
                $tinh_trang = $this->_seokey[4];
                $ID = $this->_seokey[5];

                $rs_doi_tinh_trang = $this->md_modules_update_Status_Module(trim($ID), $tinh_trang);

                if ($rs_doi_tinh_trang) {

                    return $this->index_action();
                } else {
                    echo 'error';
                }
                break;
            case "delete":
                $ID = $this->_seokey[4];
                $rs = $this->md_modules_delete_Module($ID);

                if ($rs) {

                    return $this->index_action();
                }

                break;
            default:
                break;
        }
    }

    public function add_action() {

		/* Check permission */
	   if( !$this->per_check_permission('add',true) )
	   {
		   $this->_layout ='error';
		   $strHtmlContent = $this->_['not_permission'];
		 
	   }else{
		
			/* data app */
			$this->_layout = 'iframe';
			$apps = '';
			$modules = '';
			//data lang
			$strOkHtml_header_tab = "";
			$strOkHtml_tab = "";
			$list_lang = $this->md_modules_get_list_lang();
			$arrfile = '';
			$arrlistfile = array();
			$arrlistmodule = array();
			$list_module = '';
			$module = '';
			$id_lang = '';
			$list_file = '';

			$result = FALSE;
			$id_mod_new = 0;
			$this->_['label-error'] = '';
			/* ================= end Khai bao bien ==================== */
			/* =================save data============================= */
			$module_title_def = '';
			$this->_['href_cancel'] = $status_href = URL_BASE . $this->_seokey[0] . '/' . $this->_seokey[1];
			if (isset($_POST) && !empty($_POST)) {

				$module_name = isset($_POST["modulename_" . LANG]) && $_POST["modulename_" . LANG] != '' ? $_POST["modulename_" . LANG] : '';
				$module_title_def = isset($_POST["moduletitle_" . LANG]) && $_POST["moduletitle_" . LANG] != '' ? $_POST["moduletitle_" . LANG] : '';

				$app = isset($_POST["app_id"]) && $_POST["app_id"] != '' ? $_POST["app_id"] : '';
				;
				$status = isset($_POST["status_" . LANG]) ? 'true' : 'false';
				if ($module_name == '' || $app == '') {
					$rs = FALSE;
				} else {
					$rs = $this->md_modules_add_module($module_name, $app, $status);
				}
				if ($rs) {
					$id_mod_new = $rs;

					/* insert cac ngon ngu vao ban _lang */
					foreach ($list_lang as $key => $value) {
						$id_lang = $value['ID'];

						$module_title = isset($_POST["moduletitle_$id_lang"]) && $_POST["moduletitle_$id_lang"] != '' ? $_POST["moduletitle_$id_lang"] : '';
						$lang = isset($_POST["id_$id_lang"]) && $_POST["id_$id_lang"] != '' ? $_POST["id_$id_lang"] : '';
						$notes = isset($_POST["notes_$id_lang"]) && $_POST["notes_$id_lang"] != '' ? $_POST["notes_$id_lang"] : '';
						
						$status = isset($_POST["status_$id_lang"]) ? 'true' : 'false';
						if ($module_name != '' && $module_title != '') {

							$data = array(
								'id_mod_new' => $id_mod_new,
								'Name' => $module_name,
								'ModuleTitle' => $module_title,
								'AppID' => $app,
								'LangID' => $lang,
								
								'Notes' => $notes,
								'Status' => $status
							);
							$result = $this->md_modules_add_module_detail($data);
							if ($result == false) {
								$result = $this->md_modules_delete_Module($id_mod_new);
							}
						}
					}
				}
				if ($result) {

					if ($module_title_def == '') {
						$this->_['label-error'] = 'loi ';
					} else {
						$href = $this->_seokey[0] . '/' . $this->_seokey[1];
						$url = URL_BASE . $href;
						$this->request->rq_goto_window_parent($url);
					}
				} else {
					if ($module_title_def == '') {
						$this->_['label-error'] = 'loi ';
					}
					$this->_['label-error'] = 'loi ';
				}
			}
			/* ================= end save data=================================== */

			/* ================= set list ten module============================= */
			/* get list app */
			$apps = $this->md_modules_get_list_app();

			if (!empty($apps)) {
				foreach ($apps as $app) {
					/* get list com theo app */
					$modules = $this->md_modules_modules_get_list_module_by_appid($app['ID']);

					foreach ($modules as $module) {
						array_push($arrlistmodule, $module['AppID'] . '-' . $module['App'] . '-' . $module['Name']);
					}

					/* ===========get list file theo app */
					/* path to directory to scan */
					$directory = ".\\" . DIR_APP . "\\" . $app['App'] . '\\controller\\' . 'module\\';
					/* get all files with a .php extension. */
					$list_file = glob($directory . "*.php");

					foreach ($list_file as $file) {
						$arrfile = explode('.php', $file);
						$arrfile = explode('\\', $arrfile[0]);
						array_push($arrlistfile, $app['ID'] . '-' . $app['App'] . '-' . $arrfile[5]);
					}
				}
			}
			/* kiem tra xem danh sach file co trong database chua 
			  neu chua thi cho hien thi len de nguoi dung chon
			  neu da co trong database thi khong cho hien thi len */
			$isIn = true;       
			foreach ($arrlistfile as $file) {
				$isIn = in_array($file, $arrlistmodule);
				
				if ($isIn == false) {
					$arrData = explode('-', $file);
					if (!empty($arrData)) {
						$list_module .= '<option label="' . $arrData[1] . '-' . $arrData[2] .
								'" value= "' . $arrData[2] . '" >'
								. $arrData[1] . '-' . $arrData[2] . '</option>';
						$this->_['app_ID'] = $arrData[0];
					}   
				}           
			}
			if (count($arrlistfile) == count($arrlistmodule)) {
				$list_module = '<option label="' . '{khong_data}' . '" value= "' . ' {khong_data}' . '" >'
						. '{khong_data}' . '</option>';
				$this->_['no_data'] = ' nodata';
			}
			/* ================= end set list ten module============================= */

			/* get thml */
			$strHtml = $this->view->view_display('add');
			$arrHtml = $this->view->view_get_block_html($strHtml);

			/* =================set data vao html============================= */
			/* set data to tab */
			if (!empty($list_lang)) {
				foreach ($list_lang as $key => $value) {
					//set data to tab header
					$strOkHtml_header_tab .= $this->view->view_assign($arrHtml['header_tab'], array(
						'id_lang' => $value['ID'],
						'lang_name' => $value['Lang']
							));
					/* set number tab */
					$strOkHtml_tab .=$this->view->view_assign($arrHtml['tab'], array(
						'id' => $value['ID'],
						'class_hiden' => $value['ID'] != LANG ? 'hidden' : ''
							));
				}
				/* set value vao html */
				$this->_['list_module'] = $list_module;
			}
			/* =================end set data vao html============================= */

			$strHtmlContent = $this->view->view_assign_block($strHtml, array('list_tab' => $strOkHtml_tab
				, 'list_header_tab' => $strOkHtml_header_tab));
			if (!empty($this->_)) {
				$strHtmlContent = $this->view->view_assign($strHtmlContent, $this->_);
			}
		}
        return $strHtmlContent;
    }

    public function edit_action() {
	
		/* Check permission */
	   if( !$this->per_check_permission('edit',true) )
	   {
		   $this->_layout ='error';
		   $strHtmlContent = $this->_['not_permission'];
		 
	   }else{
	   
			$this->_layout = 'iframe';
			/* =================Kiem tra login============================= */

			$seokey_id = '';
			$id = ''; /* id module can edit */
			$arrHtml = '';
			$list_lang = '';
			$id_lang = '';
			$strOkHtml_header_tab = '';
			$strOkHtml_tab = '';
			/* noi dung module can chinh sua */
			$module = '';
			$result = false;
			$html_app = '';
			/* get lay id tu seo_key */
			$seokey_id = explode('-', $this->_seokey[3]);
			if (isset($seokey_id[1])) {
				$id = $seokey_id[1];
			}

			/* get list module, lang, app */
			$module = '';
			$list_lang = $this->md_modules_get_list_lang();

			/* get html */
			$strHtml = $this->view->view_display('edit');
			$arrHtml = $this->view->view_get_block_html($strHtml);

			$id_p = $id;
			$this->_['label-error'] = '';
			$this->_['href_cancel'] = $status_href = URL_BASE . $this->_seokey[0] . '/' . $this->_seokey[1];
			/* =================xu ly post de save data */
			if (isset($_POST) && !empty($_POST)) {
				$module_title_def = isset($_POST["moduletitle_" . LANG]) && $_POST["moduletitle_" . LANG] != '' ? $_POST["moduletitle_" . LANG] : '';
				foreach ($list_lang as $key => $value) {
					$id_lang = $value['ID'];
					$name = isset($_POST["modulename_$id_lang"]) && $_POST["modulename_$id_lang"] != '' ? $_POST["modulename_$id_lang"] : '';
					$title = isset($_POST["moduletitle_$id_lang"]) && $_POST["moduletitle_$id_lang"] != '' ? $_POST["moduletitle_$id_lang"] : '';

					$notes = isset($_POST["notes_$id_lang"]) && $_POST["notes_$id_lang"] != '' ? $_POST["notes_$id_lang"] : '';
				   
					if ($id_lang == LANG) {
						$status = isset($_POST["status_$id_lang"]) ? 'true' : 'false';
					}

					if ($name != '' && $title != '') {
						$data = array(
							'id_mod_new' => $id_p,
							'Name' => $name,
							'ModuleTitle' => $title,
							'LangID' => $id_lang,
						   
							'Notes' => $notes,
							'Status' => $status
						);
						if ($module_title_def == '') {
							$this->_['label-error'] = 'loi ';
						} else {
							$check = $this->md_modules_get_module_lang($id_p, $id_lang);
							/* neu lang nay da co trong data thi update    */

							if ($check) {
								$result = $this->md_modules_update_Module($data, $id_p);
							} else {/* chua co thi insert moi */
								$result = $this->md_modules_add_module_detail($data, $id_p);
							}
						}
						if ($result) {

							$href = $this->_seokey[0] . '/' . $this->_seokey[1];
							$url = URL_BASE . $href;
							$this->request->rq_goto_window_parent($url);
						} else {
							$this->_['label-error'] = 'loi ';
						}
						unset($data);
					}
				}
			}
			/* =================end xu ly post de save data

			  =================set lai data cho form=============================== */
			/* set data to tab */
			$modulename = '';

			if (!empty($list_lang)) {
				foreach ($list_lang as $key => $value) {
					$modulename = '';
					/* set data to tab header */
					$strOkHtml_header_tab .= $this->view->view_assign($arrHtml['header_tab'], array(
						'id_lang' => $value['ID'],
						'lang_name' => $value['Lang']
							));

					/* set number tab */
					$strOkHtml_tab .=$this->view->view_assign($arrHtml['tab'], array(
						'id' => $value['ID'],
						'class_hiden' => $value['ID'] != LANG ? 'hidden' : ''
							));

					$id_lang = $value['ID'];

					$module = $this->md_modules_get_list_module($id, $id_lang);

					if (!empty($module)) {

						/* data cho module Name */
						$this->_["modulename_" . $id_lang] = $module[0]['Name'];
						$this->_["moduletitle_" . $id_lang] = $module[0]['ModuleTitle'];
					   
						/* data cho notr */
						$this->_["notes_" . $id_lang] = $module[0]['Notes'];
						if ($module[0]['Status'] == 'true') {
							$this->_['checked_' . $id_lang] = 'checked="true"';
						} else {
							$this->_['checked_' . $id_lang] = '';
						}
					} else {
						$this->_["modulename_" . $id_lang] = '';
						$this->_["moduletitle_" . $id_lang] = '';
					  
						/* data cho note */
						$this->_["notes_" . $id_lang] = '';

						/* set value vao html */
						$this->_["list_app_" . $id_lang] = $html_app;
					}
				}
			}
			/* =================end set lai data cho form */
			$strHtmlContent = $this->view->view_assign_block($strHtml, array(
				'list_tab' => $strOkHtml_tab
				, 'list_header_tab' => $strOkHtml_header_tab));

			if (!empty($this->_)) {

				$strHtmlContent = $this->view->view_assign($strHtmlContent, $this->_);
			}
		}
        return $strHtmlContent;
    }

}